const { Service } = require('uni-cloud-router')
const uniID = require('uni-id')
module.exports = class UserService extends Service {
	async login({username, password}) {
		const res = await uniID.login({username, password, needPermission: true})
		if (res.code) {return res}
		await this.checkToken(res.token)
		if (this.ctx.auth.role.includes('admin')) {return res}
		const navMenu = await this.service.menu.getMenu()
		if (navMenu.length) {return res}
		return {code: 10001, message: '该账号暂无权限登录'}
	}

	async logout(token) {
		return await uniID.logout(token)
	}

	async checkToken(token) {
		const auth = await uniID.checkToken(token)
		if (auth.code) {
			// 校验失败，抛出错误信息
			this.ctx.throw('TOKEN_INVALID', `${auth.message}，${auth.code}`)
		}
		this.ctx.auth = auth // 设置当前请求的 auth 对象
	}

	async hasAdmin() {
		const {
			total
		} = await this.db.collection('uni-id-users').where({
			role: 'admin'
		}).count()

		return !!total
	}
	
	/**
	 * 是否拥有此用户
	 */
	async hasUser(username){
		const {
			total
		} = await this.db.collection('uni-id-users').where({
			username
		}).count()
		
		return !!total
	}
	
	/**
	 * 重设密码
	 * @param {String} id 用户id
	 */
	async resetPassword(id){
		const res = await this.db.collection('uni-id-users').where({
			_id:id
		}).update({password : "4396099ad202a43fbca7b77900a6f49d4d2172ab"})
		
		if (res.code) {
			// 校验失败，抛出错误信息
			this.ctx.throw('TOKEN_INVALID', `${res.message}，${res.code}`)
		}
		
		return res
	}
	
	/**
	 * 批量导入用户
	 * @param {Sting} data 数据源
	 */
	async batchImport(data){
		console.log(data.length)
		if(data.length === 1){
			return {
				code:1,
				message: '系统出错，请稍后再试'
			}
		}
		let res = [] , count = 0
		let save = async (isTeacther , data) => {
			console.log(isTeacther,data)
			let role = []
			if(isTeacther === 0){
				role.push('STUDENT')
			}else{
				role.push('TEACHER')
			}
			data.shift()
			let result = await this.service.user.saveInfo(role,data)
			console.log(result)
			return result
		}
		let res1 = await save(0 , data.data[0].data)
		let res2 = await save(1 , data.data[1].data)
		res.push(res1)
		res.push(res2)
	
		return {code:'',data:res}
	}
	
	/**
	 * 将数据存入数据库
	 * @param {Array} role 角色
	 * @param {Array} data 插入数据
	 */
	async saveInfo(role,data){
		let failCount = 0 , succCount = 0 , count = 0 , failIndex = []
		return new Promise(async(resolve , reject)=>{
			function isEnd(){
				console.log(count,data.length)
				if(++count === data.length){
					resolve({failCount,succCount,failIndex})
				}
			}
			try{
				await Promise.all(data.map(async(key , index)=>{
					let username = key[0] ? key[0].toString() : '' , nickname = key[1] ? key[1].toString() : '' , 
					password = key[2] ? key[2].toString() : '' , college = key[3] ? key[3] : '' ,
					mobile = key[4] ? key[4].toString() : '' , email = key[5] ?  key[5].toString() : '' , 
					year = key[6] ? key[6].toString() : '' , status = 0
					const result = await uniID.register({
						username,
						nickname,
						password,
						year,
						role,
						college,
						mobile,
						email,
						status
					})
					delete result.token
					delete result.tokenExpired
					if(result.code === 20102){
						failIndex.push(index)
						failCount++
					}else{
						succCount++
					}
					isEnd()
					
				})
				)
			} catch(e) {
				reject(e)
			}
		})
	}
}
